<template>
    <div>
      <div style="width:70%; margin-left:40%;">
        <el-button type="success" @click="addDialogFormVisible=true">新增</el-button>
        <el-button type="danger" @click="delAllVehicles()">批量删除</el-button>
    </div><br>
   <!--  @selection-change：多选框的选项发生改变的时候会调用handleSelectionChange函数
        :data:该表格绑定数据集合-->
    <el-table :data="vehiclelist" border align="center" stripe ref="multipleTable"  tooltip-effect="dark"  
      @selection-change="handleSelectionChange" 
      style="border-radius: 6px; width:70%;margin:0px auto;box-shadow:0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)" >
      <!-- 多选框列 prop:指定该列要显示的数据属性-->
      <el-table-column type="selection" width="55" prop="vehicle_id"></el-table-column>
      <el-table-column prop="vehicle_code" label="车牌号" width="150"></el-table-column>
      <el-table-column prop="vehicle_size" label="车辆大小" width="150"></el-table-column>
      <el-table-column prop="vehicle_color" label="车辆颜色" width="150"></el-table-column>
      <!-- 如果某一列展示头像图片，需要如下写法 -->
      <el-table-column label="车辆图片" width="100px">
         <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <el-image style="width: 300px; height: 200px" :src="scope.row.vehicle_photo"></el-image>
            <el-image slot="reference"  style="width: 100%; height: 100%" :src="scope.row.vehicle_photo"></el-image>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button style=" margin-left:5%;" size="small" type="warning" @click="getOneVehicle(scope.row)">修改</el-button>
          <el-button size="small" type="danger" @click="delOneVehicle(scope.row)">删除</el-button>
          <el-button size="small" type="info" @click="updVehiclePhoto(scope.row)">上传图片</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 增加 -->
    <el-dialog title="新增车辆" :rules="rules" :visible.sync="addDialogFormVisible" width="30%">
      <el-form :model="addForm"   ref="addForm">
        <el-form-item label="车牌号" prop="vehicle_code" :label-width="formLabelWidth">
          <el-input v-model="addForm.vehicle_code"></el-input>
        </el-form-item>
        <el-form-item label="车辆大小">
          <el-select v-model="addForm.vehicle_size" placeholder="请选择车辆大小" style="width: 80%">
            <el-option label="大型车" value="大"></el-option>
            <el-option label="中型车" value="中"></el-option>
            <el-option label="小型车" value="小"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆颜色">
          <el-select v-model="addForm.vehicle_color" placeholder="请选择车辆颜色" style="width: 80%">
            <el-option label="白色" value="白色"></el-option>
            <el-option label="黑色" value="黑色"></el-option>
            <el-option label="红色" value="红色"></el-option>
            <el-option label="蓝色" value="蓝色"></el-option>
            <el-option label="银色" value="银色"></el-option>
            <el-option label="灰色" value="灰色"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm1('addForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改车辆信息" :visible.sync="updDialogFormVisible" width="30%">
      <el-form :model="updForm" :rules="rules1"  ref="updForm">
        <el-form-item label="车牌号" prop="vehicle_code" :label-width="formLabelWidth">
          <el-input v-model="updForm.vehicle_code"></el-input>
        </el-form-item>
        <el-form-item label="车辆大小">
          <el-select v-model="updForm.vehicle_size" placeholder="请选择" style="width: 80%">
            <el-option label="大型车" value="大"></el-option>
            <el-option label="中型车" value="中"></el-option>
            <el-option label="小型车" value="小"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆颜色">
          <el-select v-model="updForm.vehicle_color" placeholder="请选择" style="width: 80%">
            <el-option label="白色" value="白色"></el-option>
            <el-option label="黑色" value="黑色"></el-option>
            <el-option label="红色" value="红色"></el-option>
            <el-option label="蓝色" value="蓝色"></el-option>
            <el-option label="银色" value="银色"></el-option>
            <el-option label="灰色" value="灰色"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm2('updForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm1('updForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 图片修改 -->
    <el-dialog title="修改图片" :visible.sync="photoDialogFormVisible" width="30%">
      <el-form>
        <el-form-item label="">
          <el-upload
            ref="upload"
            :action="reqUrl"
            list-type="picture-card"
            :http-request="uploadSectionFile"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updPhoto()">上 传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let rule1 = /^$|^([京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][1-9DF][1-9ABCDEFGHJKLMNPQRSTUVWXYZ]\d{3}[1-9DF]|[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼渝川贵云藏陕甘青宁新][ABCDEFGHJKLMNPQRSTUVWXY][\dABCDEFGHJKLNMxPQRSTUVWXYZ]{5})$/;
    var validateVehicle_code = (rule, value, callback) => {
      if (!value) {
          return callback(new Error('车牌不能为空'));
      } else if(!rule1.test(value)) {
        callback(new Error('请输入正确车牌号'));
      } 
      callback();
    };
    return {
      imageUrl: "",
      reqUrl:"",
      vehiclelist: [],
      ids: [],
      addDialogFormVisible: false,
      addForm: {
        vehicle_uid: 2,
        vehicle_code: "",
        vehicle_size: "",
        vehicle_color: ""
      },
      formLabelWidth: "70px",
      updDialogFormVisible: false,
      updForm: {
        vehicle_id: "",
        vehicle_code: "",
        vehicle_size: "",
        vehicle_color: "",
        vehicle_photo: ""
      },
      photoDialogFormVisible: false,
      rules: {
        vehicle_code: [
          { validator: validateVehicle_code, trigger: 'blur' }
        ],
      },
      rules1: {
        vehicle_code: [
          { validator: validateVehicle_code, trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    selVehicle() {
      var id = sessionStorage.getItem('userId');
      this.$axios.get("/vehicle/" + id)
      .then((res) => {
        this.vehiclelist = res.data.data;
      })
      .catch((error) => {
        alert(res.data.messages);
      });
    },

    //val:array,代表的是选中所有行的数据
    handleSelectionChange(val) {
      var ids = []; //存放选中的id
      for (let item of val) {
        ids.push(item.vehicle_id);
      }
      //将选中的所有项的id放到数据模型中
      this.ids = ids;
      console.log(ids);
    },
    saveVehicle(){
      var id = sessionStorage.getItem('userId');
      this.$axios.post("/vehicle", {
        vehicle_uid:id,
        vehicle_code:this.addForm.vehicle_code,
        vehicle_size:this.addForm.vehicle_size,
        vehicle_color:this.addForm.vehicle_color
      })
      .then((res) => {
        alert(res.data.messages);
        this.addDialogFormVisible = false;
        this.$refs['addForm'].resetFields();
        this.selVehicle();
      }).catch((error) => {});
    },
    submitForm(addForm){
      this.$refs[addForm].validate((valid) => {
        if (valid) {
         this.saveVehicle();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    getOneVehicle(row){
      this.updDialogFormVisible = true;
      this.$axios.post("/vehicle/"+row.vehicle_id)
      .then(res => {
        this.updForm=res.data.data;
      }).catch(error => {})
    },
    submitForm1(updForm){
      this.$refs[updForm].validate((valid) => {
        if (valid) {
         this.saveUpdVehicle();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    saveUpdVehicle(){
      this.$axios.put("/vehicle", this.updForm)
      .then((res) => {
        alert(res.data.messages);
        this.updDialogFormVisible = false;
        this.selVehicle();
      }).catch((error) => {});
    },
    updVehiclePhoto(row){
      this.photoDialogFormVisible = true;
      this.updForm.vehicle_id = row.vehicle_id;
      this.updVehPhoto();
    },
    updPhoto(){
      let formData = new FormData();
      formData.append("vehicle_id", this.updForm.vehicle_id);
      formData.append("vehiclePhoto", this.updForm.vehicle_photo);
      console.log(this.updForm.vehicle_photo);
      if(this.updForm.vehicle_photo == "error" || this.updForm.vehicle_photo == ""){
        alert("请上传小于2M的JPG格式的图片");
      }
      else{
        let config = {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };
        this.$axios.post("/vehicle/photo", formData, config)
        .then((res) => {
          alert(res.data.messages);
          this.photoDialogFormVisible = false;
          this.$refs.upload.clearFiles();
          this.selVehicle();
        }).catch((error) => {});
      }
    },
    delAllVehicles() {
      this.$axios.post("/vehicle/del", this.ids)
      .then((res) => {
        alert(res.data.messages);
        this.selVehicle();
      })
      .catch((error) => {});
    },
    delOneVehicle(row){
      this.$axios.delete("/vehicle/"+row.vehicle_id)
      .then(res => {
          alert(res.data.messages);
          this.selVehicle();
      }).catch(error => {})
    },
    resetForm1(addForm) {
      this.$refs[addForm].resetFields();
      this.addDialogFormVisible = false;
      this.addForm.vehicle_size="";
      this.addForm.vehicle_color="";
    },
    resetForm2(updForm) {
      this.$refs[updForm].resetFields();
      this.updDialogFormVisible = false;
    },
    uploadSectionFile(params){
      this.updForm.vehicle_photo =params.file;
    },
    getFile(e) {
      this.updForm.vehicle_photo = e.target.files[0];
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  mounted() {
    this.selVehicle();
  },
};
</script>

<style>
</style>